package cn.tedu.store.admin.webapi.security;

import cn.tedu.store.admin.webapi.mapper.AdminMapper;
import cn.tedu.store.commons.pojo.admin.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Spring Security调用了loadUserByUsername()方法,参数: {}", s);
        AdminLoginInfoVO queryResult = adminMapper.getLoginInfoByUsername(s);
        log.debug("从数据库中匹配到与[{}用户]信息匹配, 数据为{}", s, queryResult);

        if (queryResult == null) {
            log.debug("此用户名[{}]不存在,将抛出异常!", s);
            String message = "登录失败,用户名不存在!";
            throw new BadCredentialsException(message);
        }

        List<GrantedAuthority> authorities = new ArrayList<>();
        List<String> permissions = queryResult.getPermissions();
        for (String permission : permissions) {
            GrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }

        AdminDetails adminDetails = new AdminDetails(queryResult.getUsername(), queryResult.getPassword(),
                queryResult.getEnable() == 1, authorities);
        adminDetails.setId(queryResult.getId());
        log.debug("即将向Spring Security返回UserDetails接口类型的对象：{}", adminDetails);
        return adminDetails;
    }
}
